var OrderAuditModule = function () {

    $("#investorName").autocomplete({
        source: function(query,process){
        	$.ajax({
            	"contentType":"application/json; charset=UTF-8",
                "dataType" : 'json',
                "type" : "POST",
                "url" : ctx + "/appointment/investor/"+query.term,
                "data" : {"matchCount":200},
                "success" : function(data){
                	var ebean = [];
                	var length = data.length >= 10 ? 10 : data.length;
                	for (var int = 0; int < length; int++) {
                		var temp = [];
                		temp.label = data[int].name;
                		temp.name = data[int].name;
                		temp.value = data[int].name;
                		ebean.push(temp);
            		}
                    return process(ebean);
                }
            })
        },
        search:function(event, ui){
        },
        select: function(event, ui) {
            $("#investorName").val(ui.item.name);
            var uistr =ui.item;
            // 阻止事件的默认行为
            event.preventDefault(); 
        }
    });
    
    var editable = function () {

        return {
            init: function () {
            	//格式化金额
            	function fmoney(s, n) {  
            	   if(s == ""|| undefined == s){
            		   return "--";
            	   }
                   n = n > 0 && n <= 20 ? n : 2;  
                   s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";//更改这里n数也可确定要保留的小数位  
                   var l = s.split(".")[0].split("").reverse(),  
                   r = s.split(".")[1];  
                   t = "";  
                   for(i = 0; i < l.length; i++ )  
                   {  
                      t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");  
                   }
                   var str = t.split("").reverse().join("") + "." + r.substring(0,2);
                   return str;//保留2位小数  如果要改动 把substring 最后一位数改动就可  
                }
            	
            	//表格初始化
                var oTable = $('#ordersEditable').dataTable({
                	"autoWidth":true,
                    "lengthMenu": [
                        [10, 15, 20, 50],
                        [10, 15, 20, 50]
                    ],
                    "scrollX":true,
                    "displayLength": 10,
                    "language": {
                        "lengthMenu": "每页 _MENU_ 条记录",
                        "zeroRecords":"数据为空",
                        "paginate": {
                            "previous": "上一页",
                            "next": "下一页"
                        },
                        "info" : "从 _START_ 到  _END_ 条，总记录为 _TOTAL_ 条",    
                        "infoEmpty" : "记录数为0",
                    },
                    "columnDefs": [
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "Edit",
						    "targets": [6]
						}            
                    ],
                    "columns": [
                       { "data": "orderId" ,'sortable': false,"defaultContent": "" },
                       { "data": "investorName" ,'sortable': false,"defaultContent": "" },
                       { "data": "productBriefName" ,'sortable': false,"defaultContent": "" },
                       { "data": "orderAmount" ,'sortable': false,"defaultContent": "" },
                       { "data": "orderTime" ,'sortable': false,"defaultContent": "" },
                       { "data": "auditState" ,'sortable': false,"defaultContent": "" }
                   ],
                   "filter" : false,
                   "processing": false,
                   "serverSide": true,
                   "ajaxSource": ctx + "/orderAudit/query",
                   "serverMethod": "post",
                   "fnRowCallback" : function(nRow, aData, displayIndex) {
                	   nRow.children[0].id = aData.id;
                	   nRow.children[1].id = aData.orderId;
                	   var orderId = "<center>" + aData.orderId+ "</a>" + "</center>";
                	   var inverstor = "<center>" + aData.investorName + "<br>" + aData.investorMobile + "</a>" +"</center>";
                	   var productBriefName = "<center>" + aData.productBriefName + "</a>" + "</center>";
                	   var orderAmount = "<center>" + fmoney(aData.orderAmount) + "</center>";
                	   var orderTime = "<center>" + aData.orderTime + "</center>";
                	   var orderAudit = "";
                	   var operation = "";
                	   switch (aData.auditState) {
	                	   case (1):
	                		   orderAudit = "<center>未审核</center>";
	                	   	   operation = '<a class="audit fa fa-check-square-o fa-lg pull-left" title="审核" href="javascript:;"></a> <a class="auditList fa fa-bars fa-lg pull-left" title="审核结果列表" href="javascript:;"></a>';
	                           break;
	                	   case (2):
	                		   orderAudit = "<center>审核未通过</center>";
                	   	       operation = '<a class="audit fa fa-check-square-o fa-lg pull-left" title="审核" href="javascript:;"></a> <a class="auditList fa fa-bars fa-lg pull-left" title="审核结果列表" href="javascript:;"></a>';
	                           break;
	                	   case (3):
	                		   orderAudit = "<center>审核已通过</center>";
                	   	   	   operation = '<a class="auditList fa fa-bars fa-lg pull-left" title="审核结果列表" href="javascript:;"></a>';
	                           break;
	                       default:
	                    	   orderAudit = "<center>未审核</center>";
                	   	       operation = '<a class="audit fa fa-check-square-o fa-lg pull-left" title="审核" href="javascript:;"></a> <a class="auditList fa fa-bars fa-lg pull-left" title="审核结果列表" href="javascript:;"></a>';
                	   }
                	  
                	   $('td:eq(0)', nRow).html(orderId);
                	   $('td:eq(1)', nRow).html(inverstor);
                	   $('td:eq(2)', nRow).html(productBriefName);
                	   $('td:eq(3)', nRow).html(orderAmount);
                	   $('td:eq(4)', nRow).html(orderTime);
                	   $('td:eq(5)', nRow).html(orderAudit);
                	   $('td:eq(6)', nRow).html(operation);
                       return nRow;
                   },
                   "fnServerData" : function(ajaxSource, dataSet, fnCallback) {
	                   var json = "";
	                   var s;
	                   for (var i = 0; i < dataSet.length; i++) {
	                       s = dataSet[i];
	                   	   if (s.name == 'sEcho') {
	                   		   json = json + '"echo":' + s.value;
		                   } else if (s.name == 'iDisplayStart') {
		                	   json = json + ',"page":' + s.value;
		                   } else if (s.name == 'iDisplayLength') {
		                	   json = json + ',"pageSize":' + s.value;
		                   }
	                   }
	                   
	                   var form = $("form#queryForm").serializeJSON();
                   	   var js = form.replace('}', ',');
                   	   json = js + json +'}';
                       $.ajax({
                       	   "contentType":"application/json; charset=UTF-8",
                           "dataType" : 'json',
                           "type" : "POST",
                           "url" : ajaxSource,
                           "data" : json,
                           "success" : fnCallback
                       });
                   },
                });
                
                // 审核列表
                $('#ordersEditable').on("click", "a.auditList", (function (e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[1].id;
                    
                    $.ajax({
                    	type:"post",
                        url: ctx + "/auditRecord/list/",
                        data:"orderId=" + id,
                        dataType:"json",
                        success: function(msg){
                        	$("#auditListBody").empty();// clean
                        	var auditList = {"auditList" : msg};
                        	var tmpl = $("#auditListTemplate").tmpl(auditList).appendTo("#auditListBody");
                        	
                        	var modal = $('#auditListModel').modal('show');
                        	modal.on("hidden.bs.modal",function(e){
                        		$(this).removeData();
                        	});
                        	
                        	
                        },
                        error: function (msg) {
                        	bootbox.alert(msg.message);
                        }
                    });
                }));
                
                // 审核，要先查询该订单的凭证文件，用来展示
                $('#ordersEditable').on("click", "a.audit", (function (e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[1].id;
                    
                    $.ajax({
                    	type:"post",
                        url: ctx + "/auditRecord/voucherList/",
                        data:"orderId=" + id,
                        dataType:"json",
                        success: function(msg){
                        	$("#auditBody").empty();
//                        	var auditList = {"auditList" : msg};
                        	if(msg.voucherList != undefined || msg.voucherList.length != 0){
                        		for(var i = 0;i < msg.voucherList.length; i++){
                        			msg.voucherList[i].filePath = imagePrefix + msg.voucherList[i].filePath;
                        		}
                        	}
                        	msg.orderId = id;
                        	var tmpl = $("#auditTemplate").tmpl(msg).appendTo("#auditBody");
                        	var modal = $('#auditModel').modal('show');
                        	modal.on("hidden.bs.modal",function(e){
                        		$(this).removeData();
                        	});
                        	$('#auditBtn').click(function(){
                        		var json = $("form#auditForm").serializeJSON();
                        		$('#auditBtn').attr('disabled',"true");
                        		$.ajax({
                        			"contentType":"application/json; charset=UTF-8",
                                	type:"post",
                                    url: ctx + "/auditRecord/doAdd/",
                                    data: json,
                                    dataType:"json",
                                    success: function(msg){
                                    	if(msg.code == 1){
                                    		bootbox.alert("操作成功");
                                    		$('#auditModel').modal('hide');
                                    		$('#auditBtn').removeAttr("disabled");
                                    		oTable.fnClearTable();
                                    	}else{
                                    		bootbox.alert(msg.message);
                                    		$('#auditModel').modal('hide');
                                    		$('#auditBtn').removeAttr("disabled");
                                    	}
                                    },
                                    error: function (msg) {
                                    	bootbox.alert(msg.message);
                                    	$('#auditModel').modal('hide');
                                    }
                                });
                            });
                        },
                        error: function (msg) {
                        	bootbox.alert(msg.message);
                        }
                    });
                }));
                
                //重置查询
                $('#cancelQuery').click(function(){
                	//重置按钮 清空datepicker缓存
                	$('#orderTimeStart').datepicker('setDate', null);
                	$('#orderTimeEnd').datepicker('setDate', null);
                });
                
                //查询
                $('#queryBtn').click(function(){
                	oTable.fnClearTable();
                });
                
                // 导出excel
                $('#exportExcel').click(function(){
                	var json = $("form#queryForm").serializeJSON();
                	
                	var form=$("<form>");
                	form.attr("style","display:none");
                	form.attr("target","");
                	form.attr("method","post");
                	form.attr("action",ctx + "/orderAudit/export");
                	
                	var paramsInput=$("<input>");
                	paramsInput.attr("type","hidden");
                	paramsInput.attr("name","params");
                	paramsInput.attr("value", json);
                	
                	form.append(paramsInput);
                	
                	$("body").append(form);
                	
                	form.submit();
                });
            }

        };

    }();
    
    return {
        init: function () {
        	editable.init();
        }
    };
}();